/**
 * Created by liuqingxia on 2016/2/22.
 */
var url = getRoot() + "/job/history/find";
$(document).ready(function () {

    LTS.colFormatter.optFormat = function (v, row) {
        return '<a href="javascript:;" class="log-query-btn">' +
            '<span class="label label-info" style="font-size: 14px"><i class="fa fa-list-alt"></i>日志</span><span class="hidden lts-data">' + JSON.stringify(row.id) + '</span></a>&nbsp;';
    }

    LTS.colFormatter.stateFormat = function (v, row) {
        var state = row['state'];
        if (typeof(state) == "undefined") {
            return "状态未知";
        }
        state = $.trim(state);
        if (state === "") {
            return "状态未知";
        }
        state = parseInt(state);
        if (state < 0 || state > 6) {
            if (state == 255) {
                return "UNKNOWN(255)";
            } else {
                return "状态未知";
            }
        }
        var result = switchState(state);
        return result;
    }

    /*根据state值转换成对应的提示信息*/
    function switchState(state) {
        var result;
        switch (state) {
            case 0:
                result = "执行成功";
                break;
            case 1:
                result = "提交成功";
                break;
            case 2:
                result = "初始化";
                break;
            case 3:
                result = "运行中";
                break;
            case 4:
                result = "执行失败";
                break;
            case 5:
                result = "被终止";
                break;
            case 6:
                result = "暂停";
                break;
            default :
                result = "状态未知";
                break;
        }
        return result;
    }

    var ltsTable = $("#job-table-container").ltsTable({
        url: url,
        templateId: 'job-table'
    });

    $(document).on("click", "#searchBtn", function () {
        var params = {};
        $.each($('#job-history-query-form').find(".form-control"), function () {
            var name = $(this).attr("name");
            if (!isNull(name)) {
                var value = $(this).val();
                params[name] = value;
            }
        });
        ltsTable.post(params, 1);
    });

    clickLogQueryBtn();
    closeModal();

    var jobId = $("#jobId-span").html();
    if (!isNull(jobId)) {
        jobId = $.trim(jobId);
        var params = {};
        params['jobId'] = jobId;
        $("#jobId-span").empty();
        ltsTable.post(params, 1);
    }
});


var readLogFileIntervalId;
var currentHistoryId;
var logFileBeginIndex = 0;
var readEndCount = 0;
var executeIp;

/**
 * 点击日志查询按钮
 */
function clickLogQueryBtn() {

    $(document).on("click", ".log-query-btn", function () {

        currentHistoryId = parseInt($(this).find("span.lts-data").html());
        executeIp = $.trim($(this).parent().parent().find("td.executeIp").html());
        console.log("executeIp:" + executeIp);
        if (typeof readLogFileIntervalId != "undefined") {/*虽然关闭模态框时，已经关闭定时任务，但此处还是有必要*/
            closeReadFileInterval(readLogFileIntervalId);
        }
        emptyLogContent();
        $("#history-log-modal").modal("show");
        readLogFileIntervalId = self.setInterval("readLogFileInterval(currentHistoryId)", 1000);
        console.log("readLogFileIntervalId:" + readLogFileIntervalId);

    });
}

/**
 * 关闭读取日志文件定时任务
 * @param id
 */
function closeReadFileInterval(id) {
    window.clearInterval(readLogFileIntervalId);
    readEndCount = 0;
    logFileBeginIndex = 0;
}

/**
 * 关闭模态框
 */
function closeModal() {
    $(document).on("click", "button.close", function () {
        closeReadFileInterval(readLogFileIntervalId);
    });
}

/**
 * 定时读取日志文件
 *
 * @param historyId
 */
function readLogFileInterval(historyId) {

    //if (readEndCount > 10) {/*默认10秒里没有写入新的内容，就认为写入完毕*/
    //    closeReadFileInterval(readLogFileIntervalId);
    //    return;
    //}

    readLogFile(historyId, logFileBeginIndex);
    return;
}

/**
 * 异步显示日志文件
 * @param resultMap
 */
function asyncReadLogFile(resultMap) {
    var count;
    console.log(count++);

    var errorMsg = resultMap['errorMsg'];
    if (!isNull(errorMsg)) {
        closeReadFileInterval(readLogFileIntervalId);
        showErrorMsg(errorMsg);
        return;
    }

    if (resultMap['beginIndex'] == -2) {
        //readEndCount++;
        return;
    }
    //
    //if (readEndCount != 0) {
    //    readEndCount = 0;
    //}

    logFileBeginIndex = resultMap['beginIndex'];
    var logContent = resultMap['result'];
    showLogContentAtEnd(logContent);

    setScrollEnd();
}

/**
 * 在日志显示区添加新读取到的内容
 * @param logContent
 */
function showLogContentAtEnd(logContent) {
    $("#history-log-pre").append(logContent);
}

/**
 * 显示错误信息
 */
function showErrorMsg(errorMsg) {
    $("#history-log-pre").append("<br><span style='color: red;font-weight: 900'>" + errorMsg + "</span>");
}

/**
 * 清空日志显示区
 */
function emptyLogContent() {
    $("#history-log-pre").empty();
}


/**
 * 读取日志文件内容
 * @param historyId,记录日志Id
 * @param beginIndex,文件读取位置
 */
function readLogFile(historyId, beginIndex) {

    var resultMap = {};

    $.ajax({
        type: "get",
        url: "http://" + executeIp + "/datax-console/api/log?historyJobId=" + historyId + "&beginIndex=" + beginIndex,
        dataType: 'jsonp',
        jsonp: 'callback',
        success: function (json) {
            $.extend(resultMap, json);
            asyncReadLogFile(resultMap);
        }
    });

}

function setScrollEnd() {
    var jobEditModal = $("#job-edit-modal");
    jobEditModal.scrollTop(300);
}
